package core.util;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import com.danga.MemCached.MemCachedClient;

/**
 * test从网上找的例子先测试一下
 * @author Administrator
 *
 */
public class Memcached extends MemcachConfig{
  private static MemCachedClient mcc;
  
  public static void initConfig(boolean isLoad) {
    if ( isLoad ) {
      mcc = initConfig( mcc );
      //clear();
    }
  }
  
  public static MemCachedClient getCached() {
    return mcc;
  }
  
  public static void put( String key, Object value ) {
    mcc.set(key, value);
  }
  public static Object get( String key ) {
    return mcc.get(key);
  }
  /**
   * 是否存在key
   * @param key
   * @return
   */
  public static boolean containsKey( String key ) {
    return mcc.keyExists(key);
  }
  
  /**
   * 清空缓存(需要从新写一个，flushAll不会清除缓存内容，而是设置过期时间)
   */
  public static void clear() {
    List<String> keys =  getAllKeys();
    for (String key : keys ) {
      System.out.println("------->>>>>>"+ key);
      mcc.delete(CommUtils.decode(key) );
      System.out.println("------->>>>>>"+ mcc.get(key));
    }
  }
  
  public static List<String> getAllKeys() {
    List<String> list = new ArrayList<String>();
    Map<String, Map<String, String>> items = mcc.statsItems();
    for (Iterator<String> itemIt = items.keySet().iterator(); itemIt.hasNext();) {
      String itemKey = itemIt.next();
      Map<String, String> maps = items.get(itemKey);
      for (Iterator<String> mapsIt = maps.keySet().iterator(); mapsIt.hasNext();) {
        String mapsKey = mapsIt.next();
        String mapsValue = maps.get(mapsKey);
        if (mapsKey.endsWith("number")) {// memcached key 类型
                                         // item_str:integer:number_str,是我们保存的数据
          String[] arr = mapsKey.split(":");
          int slabNumber = Integer.valueOf(arr[1].trim());
          int limit = Integer.valueOf(mapsValue.trim());
          Map<String, Map<String, String>> dumpMaps = mcc.statsCacheDump(slabNumber, limit);
          for (Iterator<String> dumpIt = dumpMaps.keySet().iterator(); dumpIt.hasNext();) {
            String dumpKey = dumpIt.next();
            Map<String, String> allMap = dumpMaps.get(dumpKey);
            for (Iterator<String> allIt = allMap.keySet().iterator(); allIt.hasNext();) {
              String allKey = allIt.next();
              System.out.println("***********>>>" + allKey);
              list.add(allKey.trim());
            }
          }
        }
      }
    }
    return list;

  }

  
  public static void main(String[] args) {
    mcc.set("ooooo", "123456");
    System.out.println( mcc.get("ooooo"));
    mcc.set("ooooo", "ggggggg");
    System.out.println( mcc.get("ooooo"));
  }
}
